<template>
  <div class="login-view">
    <div class="login-top-banner">
      <div class="title-text login">Login</div>
      <div class="title-text phone1" v-if="false">Enter your</div>
      <div class="title-text phone2" v-if="false">mobile phone</div>
    </div>
    <el-form class="login-form" :label-width="'0px'" :model="loginForm" status-icon ref="loginForm"
             @keyup.enter.native="submitForm('loginForm')">
      <el-form-item style="margin-left: 0;" label="Terminal" prop="userName" v-show="false">
        <el-input type="terminal" v-model="loginForm.terminal" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item class="input-username-item"
                    prop="userName">
        <el-input class="no-border-input" :style="{ 'font-size': px2rem('24px') }" type="userName"
                  @focus="focusInput" @blur="blurInput"
                  v-model="loginForm.userName"
                  autocomplete="off"
                  placeholder="Enter your Account number"></el-input>
      </el-form-item>
      <el-form-item class="input-password-item" prop="password">
        <el-input class="no-border-input" :style="{ 'font-size': px2rem('24px') }"
                  type="password"
                  @focus="focusInput" @blur="blurInput"
                  v-model="loginForm.password"
                  show-password
                  autocomplete="off"
                  placeholder="Enter your password"></el-input>
      </el-form-item>
      <div class="login-btn-container">
        <div class="remember-me-container">
          <el-checkbox v-model="remember" v-if="false">Remember me</el-checkbox>
        </div>
        <el-button class="custom-button" type="primary" @click="submitForm('loginForm')"></el-button>
      </div>
    </el-form>
    <FixedBottom v-if="!focus">
      <router-link class="register-link" to="/register">No account? Register now.</router-link>
    </FixedBottom>
  </div>
</template>

<script>
import Icp from '../components/common/Icp.vue'
import {px2rem} from "@/utils/px2rem";
import FixedBottom from "@/components/common/FixedBottom.vue";
import {Toast} from "vant";
import CryptoJS from 'crypto-js'

export default {
  name: "login",
  components: {
    FixedBottom,
    Icp
  },
  data() {
    var checkUsername = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('Please enter your Account'));
      }
      callback();
    };
    var checkPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('Please enter your password'));
      }
      callback();
    };
    return {
      focus: false,
      loginForm: {
        terminal: this.$enums.TERMINAL_TYPE.APP, // 0-web  1-app 2-pc
        userName: '',
        password: ''
      },
      passwordVisible: false,
      remember: true,
      rules: {
        userName: [{
          validator: checkUsername,
          trigger: 'blur'
        }],
        password: [{
          validator: checkPassword,
          trigger: 'blur'
        }]
      }
    };
  },
  methods: {
    blurInput() {
      this.$data.focus = false
      document.body.classList.remove('keyboard-active');
    },
    focusInput() {
      this.$data.focus = true
      document.body.classList.add('keyboard-active');
    },
    px2rem,
    // login
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(!this.loginForm.userName) {
            this.$message.error('Username cannot be empty');
          } else if(!this.loginForm.password) {
            this.$message.error('Password cannot be empty');
          }

          if(this.loginForm.userName && this.loginForm.password) {

            const psha256 = CryptoJS.SHA256(this.loginForm.password).toString()

            this.$http({
              url: "/login",
              method: 'post',
              data: {
                "terminal": 1, // 0-web 1-app
                "userName": this.loginForm.userName,
                "password": psha256
                // "password": this.loginForm.password
              }
            })
                .then((data) => {
                  // save to cookie (not safe)
                  this.setCookie('username', this.loginForm.userName);
                  this.setCookie('password', this.loginForm.password);
                  // save token
                  sessionStorage.setItem("accessToken", data.accessToken);
                  sessionStorage.setItem("refreshToken", data.refreshToken);
                  sessionStorage.setItem("code", data.code);
                  sessionStorage.setItem("psha256", psha256);

                  this.$message.success("Login Success");
                  // this.$nextTick
                  this.$router.push("/home/chat");
                  this.$store.commit('commonData/setIsShowChatConversation', false)
                })
          }
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    getCookie(name) {
      let reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
      let arr = document.cookie.match(reg)
      if (arr) {
        return unescape(arr[2]);
      }
      return '';
    },
    setCookie(name, value) {
      document.cookie = name + "=" + escape(value);
    },
    handleResize() {
      const viewportHeight = window.innerHeight;
      document.body.style.paddingBottom = `${viewportHeight - document.documentElement.clientHeight}px`;
    }
  },
  mounted() {
    window.addEventListener('resize', this.handleResize);
    this.loginForm.userName = this.getCookie("username");
    this.loginForm.password = this.getCookie("password");
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
}
</script>

<style scoped lang="scss">
::v-deep .el-icon-view:before {
  font-size: 20px;
}
.no-border-input ::v-deep .el-input__inner {
  position: relative;
  border: none;
  border-bottom: 2px solid var(--login-form-border-color);
}

.custom-button {
  background-image: var(--login-button-image);
  background-size: cover;
  border: none;
  width: 60px;
  height: 60px;
  color: transparent;
  background-color: transparent !important;
}

.custom-button:hover,
.custom-button:active,
.custom-button:focus {
  background-image: var(--login-button-image);
  background-size: cover;
  border: none;
  width: 60px;
  height: 60px;
  color: transparent;
  background-color: transparent !important;
  outline: none;
}

.login-view {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  background: var(--login-bg-color);

  .login-top-banner {
    height: 40vh;
    background-image: var(--login-banner-image);
    background-size: 100% 100%;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    padding: 4vh 30px;

    .title-text {
      font-size: 32px;
      color: var(--login-title-color);
    }

    .title-text.login {
      font-size: 35px;
      margin-bottom: 8px;
      margin-top: 10%;
    }
  }

  .register-link {
    text-align: center;
    color: var(--login-active-color);
    font-size: 16px;
    border: none;
  }

  .login-form {
    flex: 1;
    margin: 0 24px;
    opacity: 0.9;
    overflow: hidden;

    .input-username-item {
      margin-top: 30px;
      margin-bottom: 50px !important;
    }

    .input-password-item {
      margin-bottom: 40px !important;
    }

    .login-btn-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .register {
      display: flex;
      flex-direction: row-reverse;
      line-height: 40px;
      text-align: left;
      padding-left: 20px;
    }
  }
}
</style>